*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*	Estimate IV-VAM
*	----------------------------------------------------------------------------
*	IN: 	vam_analysis_file
*
*	OUT:	//name of output
			local outname 		"${city}_ivvam_\`y'_\`range'.csv"
			//name of sheet in deck
			local sheetname 	"${city}_ivvam_\`y'_\`range'"
*	----------------------------------------------------------------------------

	args sample sch_res ptype bw
	tokenize `sample', parse("_")
	local years "`5'`6'`7'`8'"

*	settings

	//define X
	local A1 OLSVAM_func
	local A2 OLSVAM_flag
	local A3 POLSVAM_func
	local A4 POLSVAM_flag
	local A5 OLSVAM_flag_3yr
	local A6 OLSVAM_flag POLSVAM_flag
	local A7 OLSVAM_func OLSVAM_flag POLSVAM_func OLSVAM_flag_3yr POLSVAM_flag

	local S1 $sectors
	local S2 $sectors
	local S3 $sectors
	local S4 $sectors
	local S5 $sectors
	local S6 $sectors
	local S7 $sectors

	local range "1 2 3 4 5 6 7"

*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


*	load

	foreach y in m {

		cap log close
		log using "${log}`sheetname'.smcl", replace

		u "${builddata}${city}_analysisfile_vam`sample'`sch_res'`bw'.dta", clear
		merge m:1 sch year using "${builddata}${city}_schoolcovs", nogen keep(1 3)

		//set variables and rename VAMs
		ivset, y(`y') ptype(`ptype')
			local Y=r(Y)
			local D=r(D)
			local Z=r(Z)
			local p=r(P)
			local S=r(S)

		rename *OLSVAM*_`y'_* *OLSVAM*_*
		rename *OLSVAM*_`ptype'_* *OLSVAM*_*

	***	IV-VAM

		foreach i in `range' {

			//import VAMs using older lagged scores
			if inlist(`i',5,7) {
				merge m:1 sch using "${builddata}${city}_analysisfile_vam`sample'`sch_res'`bw'_older_bl", nogen keep(1 3)
				cap rename *OLSVAM*_`y'_* *OLSVAM*_*
			}

			* set mediators
			local X `A`i'' `S`i''

			preserve

			//set vars
			ivset, y(`y') ptype(`ptype')
				local Z=r(Z)
				local p=r(P)
				local S=r(S)

			//remove collinear instruments
			_rmcoll `Z', forcedrop
				local Z = r(varlist)

			//remove collinear missing dummies
			_rmcoll `X', forcedrop
				local X = r(varlist)

			//restrict to lottery sample
			keep if `S'
			local controls `p' $iv_controls

			//first stage F's
			ivreg2 `Y' (`X' = `Z') `controls', first partial(`controls') r
				scalar first_F = e(widstat)
				scalar cd_F = e(cdf)

			//run ivvam
			eststo ivvam: ivvam `Y' (`X' = `Z') `controls', enroll(`D') dofc
			scalar N = e(N)
			mat b_ivvam = e(b)

			estimates drop ivvam

			//calculate sigma_beta
			ivvam_interpret `A`i'', sect(`S`i'')

			//store estimated hyperparameters for MSE calculations
			if `i' == 7 {
				local count = wordcount("`X'")
				mat hyperp_`i' = J(`=`count'+1',1,.)
				forval l = 1/`=`count'+1' {
					mat hyperp_`i'[`l',1] = b_ivvam[1,`l']
				}
				clear
				svmat hyperp_`i'
				export delimited using "${builddata}${city}_hyperparameters_`i'.csv", novarnames replace
			}

			//save
			eststo IVVAM_`i'_mbtsls
			estadd scalar N
			cap estadd scalar first_F
			cap estadd scalar cd_F

			restore

		}

	***	output

		esttab2 using "${tables}/raw/`outname'", replace se ///
			drop(*pscore* _cons *year *grade bl_*, relax) ///
			scalars(N first_F cd_F) mtitles nonumbers bfmt(j) se(j) sfmt(j)
		estimates clear

		insheet using "${tables}/raw/`outname'", clear nonames
		export excel using "${tables}${city}_tabs_`c(username)'_`c(current_date)'.xlsx", sheetreplace sheet("`sheetname'")

		log close

	}
